﻿namespace DFGK_WMS.WebAPI.Tools
{
    public class WebSocketMiddleware
    {
        private readonly WebSocketConnectManager connectionManager;
        private readonly WebSocketHandler _webSocketHandler;
        private readonly RequestDelegate _next;

        public WebSocketMiddleware(WebSocketHandler webSocketHandler, WebSocketConnectManager connectionManager, RequestDelegate next)
        {
            _webSocketHandler = webSocketHandler;
            this.connectionManager = connectionManager;
            _next = next;
        }
        // Invoke 方法用于处理 HTTP 请求
        public async Task Invoke(HttpContext context)
        {
            //判断是否为WebSocket请求
            if (context.WebSockets.IsWebSocketRequest)
            {
                var socket = await context.WebSockets.AcceptWebSocketAsync();
                var clientIpAddress = context.Connection.RemoteIpAddress?.ToString();
                connectionManager.AddSocket(clientIpAddress, socket);// 管理起来这次连接
                await _webSocketHandler.Handle(socket, clientIpAddress);
            }
            else
            {
                // 如果不是 WebSocket 请求，则继续执行下一个中间件
                await _next(context);
            }
        }
    }
}
